package com.knowif.backend.controller;

import com.github.pagehelper.PageInfo;
import com.knowif.backend.service.ProductService;
import com.knowif.pojo.Product;
import com.knowif.pojo.ProductExample;
import com.knowif.search.SearchCondition;
import com.knowif.system.model.RestBean;
import com.knowif.util.ExampleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author ：Xh
 * @date ：Created in 2019/5/6 0006 20:07
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping("/query")
    public RestBean<?> query(@RequestBody SearchCondition searchCondition){
        try {
            ProductExample productExample = ExampleUtil.buildExample(new ProductExample(), searchCondition);
            List<Product> products = productService.selectProduct(productExample);
            PageInfo<Product> pageInfo = new PageInfo<Product>(products);
            return new RestBean<>(RestBean.success_code, pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new RestBean<List<Product>>(RestBean.bad_code, "参数错误");
    }

    @PostMapping("/save")
    public RestBean<?> save(@RequestBody Product product){
        product.setCreateTime(new Date());
        if(productService.saveProduct(product)){
            return new RestBean<Object>(RestBean.success_code);
        }
        return new RestBean<Object>(RestBean.bad_code, "添加失败");
    }

    @PostMapping("/update")
    public RestBean<?> update(@RequestBody Product product){
        if(productService.updateProductNotNull(product)){
            return new RestBean<Object>(RestBean.success_code);
        }
        return new RestBean<Object>(RestBean.bad_code, "添加失败");
    }

    @DeleteMapping("/{id}")
    public RestBean<?> delete(@PathVariable("id") int id){
        if (productService.deleteProduct(id)){
            return new RestBean<Object>(RestBean.success_code);
        }
        return new RestBean<Object>(RestBean.bad_code, "删除失败");
    }
}